/* eslint-disable array-callback-return */
import React from 'react';
import { connect } from 'dva';
import { ExclamationCircleOutlined, UploadOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Card,
  Button,
  Col,
  Row,
  Radio,
  DatePicker,
  Input,
  InputNumber,
  Select,
  Upload,
  message,
  Modal,
  Cascader,
  Spin,
  Tooltip,
} from 'antd';
import router from 'umi/router';
import FooterToolbar from '@/components/FooterToolbar';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { requestHeadersMd5 } from '@/utils/utils';
import HOCSelect from '@/components/AntDesign/Select';

const { Option } = Select;
const { RangePicker } = DatePicker;
const { TextArea } = Input;
const FormItem = Form.Item;
const { confirm } = Modal;

@connect(({ busicont, loading }) => ({
  pageData: busicont.pageData,
  loading: loading.models.busicont || loading.models.publicdata,
  expandForm: busicont.expandForm,
  activeKey: busicont.activeKey,
  formFieldsValue: busicont.formFieldsValue,
}))
@Form.create()
class BasicForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      // 字典列表：服务类型、顺延方式、付款方式、收费规则、客户付款周期、资料收取方式、发票交付类型、发票交付方式、发票方式、发票类型、拆分规则、付款日期选择方式、产品类型、附件类型、垫付设置、是否全额
      dictList: [
        'INDST_CODE',
        'CORP_NATURE',
        'SER_TYPE',
        'POS_WAY',
        'PAY_WAY',
        'FEE_RULE',
        'CUST_PAY_PERIOD',
        'SEND_MAT_COLT_WAY',
        'INV_DELV_TYPE',
        'INV_DELV_WAY',
        'INV_CATE',
        'INV_TYPE',
        'SPLIT_RULES',
        'SELECTION_TYPE',
        'PD_CATE',
        'AFFIX_TYPE',
        'CONT_SPOT',
        'YES_NO_FLAG',
      ],
      POS_WAY: [],
      PAY_WAY: [],
      FEE_RULE: [],
      CUST_PAY_PERIOD: [],

      supplyList: [],
      depList: [],
      signUserList: [],
      posNum: '1',
      custList: [],
      uploadUrl: '/csApi/fileServer/uploadFile',
      downloadUrl: '/csApi/fileServer/downloadFile',
      fileList: [],
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const { dictList } = this.state;
    dispatch({
      type: 'publicdata/fetchDictCode',
      payload: dictList,
    }).then(data => {
      const sortNumber = (a, b) => a.itemCode - b.itemCode;
      dictList.map(dict => {
        this.setState({ [dict]: data[dict].sort(sortNumber) });
      });
    });
    // 获取供应商名称列表数据
    dispatch({
      type: 'busicont/getListByUser',
      payload: {
        name: null,
      },
    }).then(response => {
      if (response.success && response.data) {
        this.setState({ supplyList: response.data });
        // 获取签署部门列表
        this.getSignDepList(null, data => {
          data.map(item => {
            const temp = item;
            temp.label = item.name;
            temp.value = item.orgId;
            temp.isLeaf = item.leafFlag === 1;
          });
          this.setState({ depList: data });
        });
      } else {
        message.warning(`${response.message || '暂无供应商数据！'}`);
      }
    });
  }

  // 查询签署部门列表
  getSignDepList = (parentId, callback) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'busicont/fetchBaseDepart',
      payload: { parentId },
    }).then(response => {
      if (response.success && response.data.length) {
        callback(response.data);
      } else {
        message.warning(`${response.message || '暂无签署部门数据！'}`);
      }
    });
  };

  // 选择签署部门
  selectSignDep = value => {
    const { dispatch, form } = this.props;
    form.resetFields(['signId']); // 重置签署人
    const orgId = value[value.length - 1];
    dispatch({
      type: 'busicont/queryUserList',
      payload: { orgId },
    }).then(response => {
      if (response.success && response.data.length) {
        this.setState({ signUserList: response.data });
      } else {
        this.setState({ signUserList: [] });
        message.warning(`${response.message || '该部门下无签署人员数据！'}`);
      }
    });
  };

  // 签署部门动态加载数据
  loadAreaData = selectedOptions => {
    const { depList } = this.state;
    const targetOption = selectedOptions[selectedOptions.length - 1];
    const parentId = selectedOptions[selectedOptions.length - 1].orgId;
    targetOption.loading = true;
    const childrenData = [];
    this.getSignDepList(parentId, data => {
      data.map(item => {
        const temp = item;
        temp.label = item.name;
        temp.value = item.orgId;
        temp.isLeaf = item.leafFlag === 1;
        childrenData.push(item);
      });
    });
    setTimeout(() => {
      targetOption.loading = false;
      targetOption.children = childrenData;
      this.setState({
        depList: [...depList],
      });
    }, 1000);
  };

  // 选择顺延方式
  selectPosWay = e => {
    this.setState({ posNum: e.target.value });
  };

  // 点击关联客户按钮
  // modalBlock = flag => {
  //   const { form } = this.props;
  //   form.resetFields(['nameone', 'nametwo', 'no', 'uniCreditCode', 'corpNature', 'industryCode']);
  //   // this.setState({
  //   //   modalVisible: !!flag,
  //   // });
  // };

  // 删除数据
  delList = custId => {
    const { custList } = this.state;
    const newData = custList.filter(item => item.custId !== custId);
    this.setState({ custList: newData });
  };

  // getCustNametwo = uniCreditCode => {
  //   this.setState({ relationCust: uniCreditCode });
  // };

  custListadfa = custData => {
    const { custList } = this.state;
    const newcustList = custList;
    custData.map(item => {
      newcustList.push(item);
    });
    const result = [];
    const obj = {};
    for (let i = 0; i < newcustList.length; i += 1) {
      if (!obj[newcustList[i].custId]) {
        result.push(newcustList[i]);
        obj[newcustList[i].custId] = true;
      }
    }
    this.setState({
      custList: result,
    });
  };

  // 文件上传
  changeUpload = ({ file, fileList }, listContFile, getFieldName) => {
    const { downloadUrl } = this.state;
    const { form } = this.props;
    const newData = listContFile.map(item => ({ ...item }));
    if (file.status === 'done' && file.response.success) {
      const fileId = file.response.data.split('|')[0];
      const fileName = file.response.data.split('|')[1];
      fileList.map(files => {
        const temp = files;
        temp.url = `${downloadUrl}?fileId=${fileId}&fileName=${fileName}`;
        temp.linkProps = { download: `${fileName}` };
      });
      newData.push({
        uid: file.uid,
        fileFileid: fileId,
        fileName,
        fileUrl: `${downloadUrl}?fileId=${fileId}&fileName=${fileName}`,
      });
      form.setFieldsValue({ [getFieldName]: newData });
      this.setState({ [getFieldName]: newData });
      message.success('文件上传成功！');
    }
    if ((file.status === 'done' && !file.response.success) || file.status === 'error') {
      fileList.map(files => {
        const temp = files;
        temp.status = 'error';
        temp.response = '服务端错误';
      });
      const newDatas = fileList.filter(item => item.uid !== file.uid);
      form.setFieldsValue({ [getFieldName]: newDatas });
      this.setState({ [getFieldName]: newDatas });
      message.error('上传失败！');
    }
  };

  // 移除文件
  removeFile = (file, listContFile, getFieldName) => {
    const { form } = this.props;
    const newData = listContFile.filter(item => item.uid !== file.uid);
    form.setFieldsValue({ [getFieldName]: newData });
    this.setState({ [getFieldName]: newData });
  };

  // 提交数据
  sumSubmit = () => {
    const { fileList } = this.state;
    const { dispatch, form } = this.props;
    let submitData = {};
    form.validateFieldsAndScroll((err, values) => {
      const tempValues = values;
      if (!err) {
        if (fileList.length) {
          fileList.map(f => {
            const temp = f;
            delete temp.uid;
          });
        }
        tempValues.signDate = values.signDate.format('YYYY-MM-DD');
        tempValues.beginDate = values.validityPeriod.length
          ? values.validityPeriod[0].format('YYYY-MM-DD')
          : '';
        tempValues.endDate = values.validityPeriod.length
          ? values.validityPeriod[1].format('YYYY-MM-DD')
          : '';
        delete tempValues.validityPeriod;
        delete tempValues.fileList;
        Object.keys(values).forEach(key => {
          const objValues = values;
          if (values[key] && key === 'crmCustContConfig') {
            Object.keys(values[key]).forEach(k => {
              const objs = values[key];
              if (objs[k] && objs[k].key) {
                objs[k] = objs[k].key;
              } else if ((k === 'splitFlag' || k === 'paidFlag') && (!objs[k] || !objs[k].length)) {
                objs[k] = [];
              } else {
                objs[k] = objs[k] ? objs[k] : null;
              }
            });
          } else if (values[key] && values[key].key) {
            objValues[key] = values[key].key;
            if (key === 'selectionType') {
              objValues.defaultAccoPeriod[key] = values[key];
              objValues.defaultAccoPeriod.pdCode = '0';
              delete objValues[key];
            }
          } else if (key === 'signDepId' && values[key].length) {
            objValues[key] = values[key][values[key].length - 1];
          } else {
            objValues[key] = values[key] ? values[key] : null;
          }
        });

        // submitData = { ...values, custList, fileList };
        submitData = { ...values, fileList };
        // if (submitData.custList && submitData.custList.length) {
        dispatch({
          type: 'busicont/suppContSubmit',
          payload: submitData,
        }).then(response => {
          if (response.success) {
            message.success(`${response.message || '新增成功！'}`);
            confirm({
              icon: <QuestionCircleOutlined />,
              title: '是否添加报价单?',
              okText: '是',
              okType: 'default',
              cancelText: '否',
              style: { top: 200 },
              onOk() {
                router.push(
                  encodeURI(
                    `/salemanage/quotation/add?comType=${2}&suppId=${response.data.suppId}&contId=${
                      response.data.suppContId
                    }`
                  )
                );
              },
              onCancel() {
                dispatch({
                  type: 'busicont/updateModalData',
                  payload: {
                    formFieldsValue: {},
                    activeKey: '2',
                    expandForm: false,
                    pageData: {
                      pagination: {
                        current: 1,
                        pageSize: 10,
                        total: 10,
                      },
                    },
                  },
                });
                router.push('/salemanage/busicont/index?activeKey=2');
              },
            });
          } else {
            message.warning(`${response.message || '新增失败！'}`);
          }
        });
        // } else {
        //   message.warning('请至少关联一个客户');
        // }
      }
    });
  };

  // 取消
  cancel = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'busicont/updateModalData',
      payload: {
        formFieldsValue: {},
        activeKey: '2',
        expandForm: false,
        pageData: {
          pagination: {
            current: 1,
            pageSize: 10,
            total: 10,
          },
        },
      },
    });
    router.push('/salemanage/busicont/index?activeKey=2');
  };

  // 渲染函数
  render() {
    const {
      supplyList,
      depList,
      signUserList,
      POS_WAY,
      posNum,
      PAY_WAY,
      uploadUrl,
      fileList,
      CUST_PAY_PERIOD,
      FEE_RULE,
    } = this.state;
    const {
      form: { getFieldDecorator },
    } = this.props;
    const { loading } = this.props;
    // 上传部分
    const uploadFileFormat = e => {
      if (Array.isArray(e)) {
        return e;
      }
      return e && e.fileList;
    };
    // 其他文件
    const propsUpload = {
      action: uploadUrl,
      headers: requestHeadersMd5(),
      onChange: info => this.changeUpload(info, fileList, 'fileList'),
    };

    // 表单布局
    const xl = { span: 8 };
    const lg = { span: 8 };
    const md = { span: 8 };
    const sm = 24;
    const colProps = { xl, lg, md, sm };
    // 下拉列表
    // 字典下拉
    const dictOL = dictList =>
      dictList.map(options => <Option key={options.itemCode}>{options.itemName}</Option>);
    // 签署人选项
    const signUserOL = signUserList.map(options => (
      <Option key={options.userId}>{options.userName}</Option>
    ));
    // 签约方
    const supplyOL = supplyList.map(options => (
      <Option key={options.suppId} title={options.name}>
        {options.name}
      </Option>
    ));
    return (
      <Spin tip="Loading..." spinning={loading}>
        <Form layout="vertical">
          <PageHeaderWrapper>
            <Card title={<span style={{ fontWeight: 'bolder' }}>供应商合同</span>}>
              <Row gutter={64}>
                <Col {...colProps}>
                  <FormItem label="供应商名称">
                    {getFieldDecorator('suppId', {
                      rules: [{ required: true, message: '请选择' }],
                    })(
                      <HOCSelect
                        placeholder="请输入关键字检索"
                        labelInValue
                        showSearch
                        optionFilterProp="children"
                        allowClear
                      >
                        {supplyOL}
                      </HOCSelect>
                    )}
                  </FormItem>
                </Col>
                <Col {...colProps}>
                  <FormItem label="合同名称">
                    {getFieldDecorator('contName', {
                      rules: [{ required: true, message: '最多不超过100字符', max: 100 }],
                    })(<Input placeholder="请输入" maxLength={100} />)}
                  </FormItem>
                </Col>
                <Col {...colProps}>
                  <FormItem label="签约日期">
                    {getFieldDecorator('signDate', {
                      rules: [{ required: true, message: '请选择' }],
                    })(<DatePicker placeholder="请选择" style={{ width: '100%' }} />)}
                  </FormItem>
                </Col>
              </Row>
              <Row gutter={64}>
                <Col {...colProps}>
                  <FormItem label="签署部门">
                    {getFieldDecorator('signDepId', {
                      rules: [{ required: true, message: '请选择' }],
                    })(
                      <Cascader
                        placeholder="请选择"
                        options={depList}
                        showSearch
                        loadData={this.loadAreaData}
                        onChange={this.selectSignDep}
                        changeOnSelect
                      />
                    )}
                  </FormItem>
                </Col>
                <Col {...colProps}>
                  <FormItem label="签署人">
                    {getFieldDecorator('signId', {
                      rules: [{ required: true, message: '请选择签署部门' }],
                    })(
                      <HOCSelect
                        placeholder="请选择"
                        labelInValue
                        showSearch
                        optionFilterProp="children"
                      >
                        {signUserOL}
                      </HOCSelect>
                    )}
                  </FormItem>
                </Col>
                <Col {...colProps}>
                  <FormItem label="合同有效期">
                    {getFieldDecorator('validityPeriod', {
                      rules: [{ required: true, message: '请选择' }],
                    })(
                      <RangePicker
                        placeholder={['开始日期', '结束日期']}
                        style={{ width: '100%' }}
                      />
                    )}
                  </FormItem>
                </Col>
              </Row>
              <Row gutter={64}>
                <Col {...colProps}>
                  <FormItem label=" 顺延方式">
                    {getFieldDecorator('posWay', {
                      initialValue: posNum,
                      rules: [{ required: true, message: '请选择' }],
                    })(
                      <Radio.Group onChange={this.selectPosWay}>
                        {POS_WAY.map(options => (
                          <Radio value={options.itemCode} key={options.itemCode}>{options.itemName}</Radio>
                        ))}
                      </Radio.Group>
                    )}
                  </FormItem>
                </Col>
                {posNum === '3' ? (
                  <Col {...colProps}>
                    <FormItem label="顺延月数">
                      {getFieldDecorator('posDate', {
                        rules: [{ required: true, message: '请输入' }],
                      })(
                        <InputNumber
                          placeholder="请输入"
                          min={1}
                          max={100}
                          style={{ width: '100%' }}
                        />
                      )}
                    </FormItem>
                  </Col>
                ) : null}
                <Col {...colProps} />
              </Row>
            </Card>
            <Card title={<span style={{ fontWeight: 'bolder' }}>合同约定</span>}>
              <Row gutter={64}>
                <Col {...colProps}>
                  <FormItem label="付款方式">
                    {getFieldDecorator('crmCustContConfig.payWay', {
                      rules: [{ required: false, message: '请选择' }],
                    })(
                      <HOCSelect
                        placeholder="请选择"
                        allowClear
                        labelInValue
                        showSearch
                        optionFilterProp="children"
                      >
                        {dictOL(PAY_WAY)}
                      </HOCSelect>
                    )}
                  </FormItem>
                </Col>
                <Col {...colProps}>
                  <FormItem label={<span>账单交付日</span>}>
                    {getFieldDecorator('crmCustContConfig.billDelvDay', {
                      rules: [{ required: false, message: '请输入' }],
                    })(
                      <InputNumber
                        min={1}
                        max={31}
                        style={{ width: '100%' }}
                        placeholder="请输入"
                      />
                    )}
                  </FormItem>
                </Col>
                <Col {...colProps}>
                  <FormItem label="发票邮寄周期">
                    {getFieldDecorator('crmCustContConfig.invPeriod', {
                      rules: [{ required: false, message: '请输入' }],
                    })(
                      <HOCSelect
                        placeholder="请选择"
                        allowClear
                        labelInValue
                        showSearch
                        optionFilterProp="children"
                      >
                        {dictOL(CUST_PAY_PERIOD)}
                      </HOCSelect>
                    )}
                  </FormItem>
                </Col>
              </Row>
            </Card>
            <Card title={<span style={{ fontWeight: 'bolder' }}>收费设置</span>}>
              <Row gutter={64}>
                <Col {...colProps}>
                  <FormItem
                    label={
                      <Tooltip
                        placement="right"
                        title={
                          <div>
                            <p>1.派单收费：增减员后可提前根据派出信息产生账单费用；</p>
                            <p>
                              2.截止日前交接收费：单流的情况下员工服务在申报截止日前提交运行后险种可生成收费账单，离职人员按照派单收费规则，减员之后直接生成账单；
                            </p>
                            <p>3.申报成功收费：增员申报成功后可生成账单费用；</p>
                            <p>
                              以上只针对本公司执行业务，涉及供应商执行的数据全部按照派单收费规则收费。
                            </p>
                          </div>
                        }
                      >
                        <span>社保收费规则</span>
                        <ExclamationCircleOutlined style={{ marginLeft: 5 }} />
                      </Tooltip>
                    }
                  >
                    {getFieldDecorator('crmCustContConfig.insFeeRule', {
                      rules: [{ required: false, message: '请选择收费规则' }],
                    })(
                      <HOCSelect
                        placeholder="请选择"
                        allowClear
                        labelInValue
                        showSearch
                        optionFilterProp="children"
                      >
                        {dictOL(FEE_RULE)}
                      </HOCSelect>
                    )}
                  </FormItem>
                </Col>
                <Col {...colProps}>
                  <FormItem
                    label={
                      <Tooltip
                        placement="right"
                        title={
                          <div>
                            <p>1.派单收费：增减员后可提前根据派出信息产生账单费用；</p>
                            <p>
                              2.截止日前交接收费：单流的情况下员工服务在申报截止日前提交运行后险种可生成收费账单，离职人员按照派单收费规则，减员之后直接生成账单；
                            </p>
                            <p>3.申报成功收费：增员申报成功后可生成账单费用；</p>
                            <p>
                              以上只针对本公司执行业务，涉及供应商执行的数据全部按照派单收费规则收费。
                            </p>
                          </div>
                        }
                      >
                        <span>公积金收费规则</span>
                        <ExclamationCircleOutlined style={{ marginLeft: 5 }} />
                      </Tooltip>
                    }
                  >
                    {getFieldDecorator('crmCustContConfig.accuFeeRule', {
                      rules: [{ required: false, message: '请选择规则' }],
                    })(
                      <HOCSelect
                        placeholder="请选择"
                        allowClear
                        labelInValue
                        showSearch
                        optionFilterProp="children"
                      >
                        {dictOL(FEE_RULE)}
                      </HOCSelect>
                    )}
                  </FormItem>
                </Col>
              </Row>
            </Card>
            {/* <Card title={<span style={{ fontWeight: 'bolder' }}>关联客户</span>}>
              <Row style={{ marginBottom: '20px' }}>
                <Button
                  type="primary"
                  onClick={() => {
                    this.modalBlock(true);
                  }}
                >
                  <Icon type="plus" />
                  关联客户
                </Button>
                {this.state.relationCust === true ? (
                  <SupplyAddModal
                    getCustNametwo={uniCreditCode => this.getCustNametwo(uniCreditCode)}
                    custListadfa={custData => this.custListadfa(custData)}
                    displayb={this.state.relationCust}
                    existing={this.state.custList}
                  />
                ) : null}
              </Row>
              <Row gutter={64}>
                {this.state.custList.map((item, index) => (
                  <Col {...colProps} key={item.custId ? item.custId : index}>
                    <div style={{ float: 'left' }}>
                      <p>{item.custName}</p>
                    </div>
                    <Icon
                      style={{ float: 'left', lineHeight: '25px' }}
                      className="dynamic-delete-button"
                      type="minus-circle-o"
                      onClick={() => this.delList(item.custId)}
                    />
                  </Col>
                ))}
              </Row>
            </Card> */}
            <Card title={<span style={{ fontWeight: 'bolder' }}>特殊要求</span>}>
              {getFieldDecorator('crmCustContConfig.speReq', {
                rules: [{ required: false, message: '200字以内' }],
              })(<TextArea rows={4} placeholder="请输入" maxLength={200} />)}
            </Card>
            <Card title={<span style={{ fontWeight: 'bolder' }}>附件</span>}>
              <Row gutter={64}>
                <Col {...colProps}>
                  <Form.Item label="其他附件:">
                    {getFieldDecorator('fileList', {
                      rules: [{ required: false, message: '请上传文件' }],
                      valuePropName: 'fileList',
                      getValueFromEvent: uploadFileFormat,
                    })(
                      <Upload {...propsUpload}>
                        <Button>
                          <UploadOutlined /> 上传附件
                        </Button>
                      </Upload>
                    )}
                  </Form.Item>
                </Col>
              </Row>
            </Card>
            <FooterToolbar style={{ width: '100%' }}>
              <Button onClick={this.cancel} style={{ marginRight: 10 }}>
                取消
              </Button>
              <Button type="primary" onClick={this.sumSubmit}>
                提交
              </Button>
            </FooterToolbar>
          </PageHeaderWrapper>
        </Form>
      </Spin>
    );
  }
}
export default BasicForm;
